package com.huanying.goodjob.lottery;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.huanying.framework.BaseController;
import com.huanying.framework.PageBean;
import com.huanying.framework.user.User;
import com.huanying.framework.user.UserService;
import com.huanying.goodjob.prize.Prize;
import com.huanying.goodjob.prize.PrizeService;
import com.huanying.goodjob.prize_chance.Prize_chance;
import com.huanying.goodjob.prize_chance.Prize_chanceService;

@Controller
public class LotteryController extends BaseController{
	private static Logger logger = Logger.getLogger(LotteryController.class);
	@Autowired
	private LotteryService lotteryService;
	@Autowired
	private UserService userService;
	@Autowired
	private PrizeService prizeservice;
	@Autowired
	private Prize_chanceService prize_chanceService;
	//查询用户的抽奖情况
	@RequestMapping("/show_add_lottery.do")
	public String show_add_lottery(String name,String day,String page_num,Model model){
		Map<String,Object> map=new HashMap<String,Object>();
		PageBean pageBean = null;
		map.put("name",name);
		map.put("day",day);
		if (page_num == null) {
			page_num = "1";
		}

		try {
			pageBean = lotteryService.search_lottery(map, super.getPageSize(), Integer.valueOf(page_num));
		} catch (NumberFormatException e) {
			logger.error("查询抽奖失败", e);
			// TODO Auto-generated catch block
		} catch (Exception e) {
			logger.error("查询抽奖失败", e);
			// TODO Auto-generated catch block
		}
		model.addAttribute("name",name);
		model.addAttribute("day",day);
		model.addAttribute("lotterys", pageBean.getList());
		model.addAttribute("page", pageBean);
		return "/lottery/add_lottery";
	}
	//将用户的抽奖情况加入表中
	@RequestMapping(value="/add_lottery.do", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String add_lottery(String user_id,String longitude,String latitude,String jsoncallback)
	{   int flag;
	    int prize_id;
	    Prize_chance prize_chance;
		Map<String,Object> map=new HashMap<String,Object>();
		flag=check_chance(user_id);
		if(flag!=0)
	 {
		prize_id=lottery_method();
	   
		Lottery lottery=new Lottery();
		User user=new User();
		Prize prize=new Prize();
		try {		
			user=userService.getbyId(Integer.parseInt(user_id));
			prize=prizeservice.get_prize(prize_id);
				 try {
						prize_chance=prize_chanceService.get_prize_chance(flag);
						prize_chanceService.update_chance_status(prize_chance.getId());
					} catch (Exception e1) {
						// TODO Auto-generated catch block
					   logger.error("添加中奖记录中的获取抽奖机会失败", e1);
					}
			if(!prize.getName().equals("谢谢参与"))
			{
			lottery.setUser(user);
			lottery.setPrize(prize);
			lottery.setLongitude(Double.parseDouble(longitude));
			lottery.setLatitude(Double.parseDouble(latitude));
			lottery.setStatus(1);
			lotteryService.add_lottery(lottery);
			}
			map.put("prize",prize);
		} catch (NumberFormatException e) {
			//  
			logger.error("添加抽奖失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("添加抽奖失败", e);
		}
		
	
		}else{
			map.put("flag","0");
		}
		Gson gson=new Gson();
		String s=gson.toJson(map);
		return jsoncallback+"("+s+")";
	}
	//后台删除记录
	@RequestMapping("/delete_lottery.do")
	@ResponseBody
	public Map<String,Object> delete_lottery(String id){
		Map<String,Object> map=new HashMap<String,Object>();
		try {
			lotteryService.delete_lottery(Integer.parseInt(id));
			map.put("flag", "1");
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("删除抽奖失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("删除抽奖失败", e);
		}
		return map;
	}
	//后台更新记录
	@RequestMapping("/update_lotterystatus.do")
	@ResponseBody
	public Map<String,Object> update_lotterystatus(String id,String status)
	{
		Map<String,Object> map=new HashMap<String,Object>();
	    try {
			lotteryService.update_lotterystatus(Integer.parseInt(id),Integer.parseInt(status));
		    map.put("flag", "1");
		    map.put("id",Integer.parseInt(id));
	    } catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("修改记录状态失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("修改记录状态失败", e);
		}
	   return map;
	}
	//后台获取单个记录
	@RequestMapping("/get_lottery.do")
	@ResponseBody
	public Map<String,Object> get_lottery(String id)
	{
		Map<String,Object> map=new HashMap<String,Object>();
		Lottery lottery;
		try {
			lottery=lotteryService.get_lottery(Integer.parseInt(id));
			map.put("lottery", lottery);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个抽奖记录失败", e);
		}
		return map;
	}
	//校验用户是否有抽奖机会
	public  int check_chance(String user_id){
		int flag=0;
		Prize_chance prize_chance;
		 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		 Date start_time;
		 Date now;
		 Date end_time;
		try {
			
			prize_chance=lotteryService.check_chance(Integer.parseInt(user_id));
		  if(prize_chance!=null)
		  {
			start_time=sdf.parse(sdf.format(prize_chance.getStart_time()));
		   now=sdf.parse(sdf.format(new Date()));
		   end_time=sdf.parse(sdf.format(prize_chance.getEnd_time()));
			if((now.getTime()-start_time.getTime())/1000>0 && (end_time.getTime()-now.getTime())/1000>0)
			{
				flag=prize_chance.getId();
			}else{
			flag=0;
			}
		  }else{
			 flag=0;
		  }
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			logger.error("校验用户失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("校验用户失败", e);
		}
		return flag;
	}
//前台获取用户的中奖记录
	@RequestMapping(value="/front_get_lotterys.do", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String front_get_lotterys(String user_id,String jsoncallback)
	{
		Map<String,Object> map=new HashMap<String,Object>();
		List<Object> list;
		try {
			list=lotteryService.front_get_lotterys(Integer.parseInt(user_id));
		    map.put("list",list);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
		     logger.error("前台获取用户抽奖记录失败", e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			 logger.error("前台获取用户抽奖记录失败", e);
		}
		Gson gson=new Gson();
		String s=gson.toJson(map);
		return jsoncallback+"("+s+")";
	}
	//前台获取单个记录
	@RequestMapping(value="/front_get_lotterybyid.do", method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String front_get_lotterybyid(String id,String jsoncallback)
	{
		Map<String,Object> map=new HashMap<String,Object>();
		Lottery lottery;
		try {
			lottery=lotteryService.get_lottery(Integer.parseInt(id));
			map.put("list", lottery);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("获取单个抽奖记录失败", e);
		}
		Gson gson=new Gson();
		String s=gson.toJson(map);
		return jsoncallback+"("+s+")";
	}
	//抽奖方法
	public int lottery_method()
	{
		List<Prize> list=null;
		try {
			list=(List<Prize>)prizeservice.get_prizeList();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("抽奖方法错误", e);
		}
		List<Double> orignalRates = new ArrayList<Double>(list.size());
		for (Prize prize :list) {
			double probability = prize.getChance();
			if (probability < 0) {
				probability = 0;
			}
			orignalRates.add(probability);
		}
		int orignalIndex = LotteryUtil.lottery(orignalRates);
		int prize_id=(list.get(orignalIndex)).getId();
		return prize_id;
	}
}
